package com.jerei.web.utils;

import com.alibaba.fastjson.JSONObject;
import com.jerei.utils.UtilsCommon;
import com.jerei.utils.spring.IEntity;
import org.apache.commons.lang3.math.NumberUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;

/**
 * Created by sunfeihu on 2016/11/7.
 */
public class UtilsWeb {

    public static JSONObject getIpInfo(String ip) throws IOException {
        if (ip == null || "127.0.0.1".equals(ip) || ip.startsWith("192.168.") || ip.equals("localhost")) {
            ip = "";
        }
        String result = UtilsHttp.doGet("\"http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + ip);
        JSONObject jsObj = null;
        try {
            jsObj = jsObj.parseObject(result);
        } catch (Exception e) {
        }
        return jsObj;
    }

    public static IEntity setDefault(IEntity entity, HttpServletRequest request) {
        if (null == entity.getAddDate()) {
            entity.setAddDate(Calendar.getInstance().getTime());
        }
        if (null == entity.getAddIp()) {
            entity.setAddIp(UtilsWeb.getIp(request));
        }
        if (null == entity.getAddUser()) {
            entity.setAddUser(UtilsWeb.getString(request, "user"));
        }
        entity.setUpdateDate(Calendar.getInstance().getTime());
        entity.setUpdateIp(UtilsWeb.getIp(request));
        entity.setUpdateUser("user");
        return entity;
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getDomain(HttpServletRequest request) {
        String domain = "";
        Integer port = request.getServerPort();
        String portStr = "";
        if (port != 80) {
            portStr += ":" + port;
        }
        domain += request.getScheme() + "://" + request.getServerName() + portStr + request.getSession().getServletContext().getContextPath();
        return domain;
    }


    public static void do301(HttpServletResponse response, String url) throws IOException {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", url);
        response.setHeader("Connection", "close");
    }

    public static void do302(HttpServletResponse response, String url) throws IOException {
        response.sendRedirect(url);
    }


    public static void doForward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception e) {

        }
    }


    public static String getAbsolutePath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/");
    }

    public static String getCookies(HttpServletRequest request, String key) {
        Cookie cookies[] = null;
        String r = null;
        try {
            cookies = request.getCookies();
            for (int i = 0; cookies != null && i < cookies.length; i++) {
                if (cookies[i].getName().equals(key)) {
                    r = URLDecoder.decode(cookies[i].getValue(), "utf-8");
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cookies = null;
        }
        return r;
    }

    public static String getRealPath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/");
    }

    public static String getString(HttpServletRequest request, String field, Boolean isSecurityFilter) {
        String value = null;
        if (null != request) {
            value = request.getParameter(field);
        }
        if (null != value) {
            if (null != isSecurityFilter && isSecurityFilter) {
                value = UtilsCommon.securityFilter(value);
            }
        }
        return UtilsCommon.getString(value);
    }


    public static String getString(HttpServletRequest request, String field) {
        return getString(request, field, true);
    }

    public static Integer getInteger(HttpServletRequest request, String field, Boolean isSecurityFilter) {
        String value = getString(request, field, isSecurityFilter);
        if ("".equals(value)) {
            return null;
        }
        return NumberUtils.toInt(value);
    }

    public static Integer getInteger(HttpServletRequest request, String field) {
        return getInteger(request, field, true);
    }

    public static Long getLong(HttpServletRequest request, String field, Boolean isSecurityFilter) {
        String value = getString(request, field, isSecurityFilter);
        if ("".equals(value)) {
            return null;
        }
        return NumberUtils.toLong(value);
    }

    public static Long getLong(HttpServletRequest request, String field) {
        return getLong(request, field, true);
    }

    public static Double getDouble(HttpServletRequest request, String field, Boolean isSecurityFilter) {
        String value = getString(request, field, isSecurityFilter);
        if ("".equals(value)) {
            return null;
        }
        return NumberUtils.toDouble(value);
    }

    public static Double getDouble(HttpServletRequest request, String field) {
        return getDouble(request, field, true);
    }

}
